﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DR5.SPExtend
{
    public static class DictionaryExtensions
    {
        public static DataTable ToDataTable<TKey, TValue>(this Dictionary<TKey, TValue> hashtable)
        {
            var dataTable = new DataTable(hashtable.GetType().Name);
            dataTable.Columns.Add(StringEx.Key, typeof(object));
            dataTable.Columns.Add(StringEx.Value, typeof(object));
            foreach (KeyValuePair<TKey, TValue> var in hashtable)
            {
                dataTable.Rows.Add(var.Key, var.Value);
            }
            return dataTable;
        }

        public static Dictionary<TKey, TValue> Adds<TKey, TValue>(this Dictionary<TKey, TValue> hashtable, TKey key, TValue value)
        {
            hashtable.Add(key, value);
            return hashtable;
        }

        public static Dictionary<string, string> AddsIfNotNull(this Dictionary<string, string> hashtable, string key, string value)
        {
            if (value.IsNotNullOrEmpty())
            {
                hashtable.Add(key, value);
            }
            return hashtable;
        }

        public static string Join(this Dictionary<string, string> pairs, string keyValueSeperator, string pairSeperator)
        {
            StringBuilder sb = new StringBuilder();

            int count = pairs.Count;
            int i = 0;
            foreach (KeyValuePair<string, string> var in pairs)
            {
                i++;
                string newStr = var.Key + keyValueSeperator + var.Value;
                if (i != count)
                {
                    newStr += pairSeperator;
                }
                sb.Append(newStr);
            }
            return sb.ToString();
        }
    }
}
